<template>
  <div class="profile-view">
    <!-- 页面头部 -->
    <div class="profile-header">
      <h1 class="page-title">{{ t('dashboard.profile.header.title') }}</h1>
      <p class="page-subtitle">{{ t('dashboard.profile.header.subtitle') }}</p>
    </div>

    <!-- 用户信息卡片 -->
    <div class="profile-card">
      <div class="avatar-section">
        <el-avatar :size="80" :src="avatarUrl">
          {{ authStore.user?.username?.charAt(0) || authStore.user?.realName?.charAt(0) }}
        </el-avatar>
        <el-button type="primary" size="small" @click="handleUploadAvatar">
          <el-icon><Camera /></el-icon>
          {{ t('dashboard.profile.card.changeAvatar') }}
        </el-button>
      </div>
      
      <div class="info-section">
        <h2 class="user-name">{{ authStore.user?.username }}</h2>
        <p class="real-name" v-if="authStore.user?.realName">{{ authStore.user?.realName }}</p>
        <p class="user-email">{{ authStore.user?.email }}</p>
        <div class="user-badges">
          <el-tag :type="roleType" size="small">{{ roleText }}</el-tag>
          <el-tag :type="statusType" size="small">{{ statusText }}</el-tag>
        </div>
      </div>

      <div class="stats-section">
        <div class="stat-item">
          <span class="stat-value">{{ formatFileSize(authStore.user?.storageUsed || 0) }}</span>
          <span class="stat-label">{{ t('dashboard.profile.card.storageUsed') }}</span>
        </div>
        <div class="stat-item">
          <span class="stat-value">{{ formatFileSize(authStore.user?.storageQuota || 0) }}</span>
          <span class="stat-label">{{ t('dashboard.profile.card.storageQuota') }}</span>
        </div>
        <div class="stat-item">
          <span class="stat-value">{{ storagePercentage }}%</span>
          <span class="stat-label">{{ t('dashboard.profile.card.usage') }}</span>
        </div>
      </div>
    </div>

    <!-- 功能选项卡 -->
    <div class="profile-tabs">
      <el-tabs v-model="activeTab" @tab-change="handleTabChange">
        <el-tab-pane :label="t('dashboard.profile.tabs.basic')" name="basic">
          <BasicInfoForm />
        </el-tab-pane>
        <el-tab-pane :label="t('dashboard.profile.tabs.security')" name="security">
          <SecuritySettings />
        </el-tab-pane>
        <el-tab-pane :label="t('dashboard.profile.tabs.storage')" name="storage">
          <StorageManagement />
        </el-tab-pane>
        <el-tab-pane :label="t('dashboard.profile.tabs.preferences')" name="preferences">
          <PreferenceSettings />
        </el-tab-pane>
      </el-tabs>
    </div>

    <!-- 头像上传对话框 -->
    <el-dialog
      v-model="avatarDialogVisible"
      :title="t('dashboard.profile.avatarDialog.title')"
      width="400px"
      :before-close="handleCloseAvatarDialog"
    >
      <div class="avatar-upload">
        <el-upload
          ref="uploadRef"
          :auto-upload="false"
          :show-file-list="false"
          :on-change="handleAvatarChange"
          accept="image/*"
          drag
        >
          <div class="upload-area">
            <el-icon class="upload-icon"><Plus /></el-icon>
            <div class="upload-text">
              <p>{{ t('dashboard.profile.avatarDialog.drag_text_1') }}</p>
              <p class="upload-hint">{{ t('dashboard.profile.avatarDialog.drag_text_2') }}</p>
            </div>
          </div>
        </el-upload>
        
        <div v-if="previewUrl" class="avatar-preview">
          <img :src="previewUrl" :alt="t('dashboard.profile.avatarDialog.preview')" />
        </div>
      </div>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="avatarDialogVisible = false">{{ t('dashboard.profile.avatarDialog.cancel') }}</el-button>
          <el-button type="primary" @click="handleConfirmUpload" :loading="uploading">
            {{ t('dashboard.profile.avatarDialog.confirm') }}
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { useI18n } from 'vue-i18n'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Camera, Plus } from '@element-plus/icons-vue'
import { useAuthStore } from '@/stores/auth'
import { uploadAvatar } from '@/api/modules/auth'
import BasicInfoForm from './components/BasicInfoForm.vue'
import SecuritySettings from './components/SecuritySettings.vue'
import StorageManagement from './components/StorageManagement.vue'
import PreferenceSettings from './components/PreferenceSettings.vue'

const authStore = useAuthStore()
const { t } = useI18n()

// 选项卡状态
const activeTab = ref('basic')

// 头像URL计算属性 - 支持默认随机头像
const avatarUrl = computed(() => {
  if (authStore.user?.avatarUrl) {
    // 添加版本号参数避免浏览器缓存
    const separator = authStore.user.avatarUrl.includes('?') ? '&' : '?'
    return `${authStore.user.avatarUrl}${separator}v=${authStore.avatarVersion}`
  }
  // 使用用户ID作为seed，确保同一用户看到相同的默认头像
  const userId = authStore.user?.id || 1
  return `https://picsum.photos/200/200?random=${userId}`
})

// 头像上传相关
const avatarDialogVisible = ref(false)
const uploading = ref(false)
const previewUrl = ref('')
const uploadRef = ref()
const selectedFile = ref<File | null>(null)

// 计算属性
const roleType = computed(() => {
  return authStore.user?.role === 'ADMIN' ? 'danger' : 'primary'
})

const roleText = computed(() => {
  return authStore.user?.role === 'ADMIN' ? t('dashboard.profile.card.roleAdmin') : t('dashboard.profile.card.roleUser')
})

const statusType = computed(() => {
  return authStore.user?.status === 'ACTIVE' ? 'success' : 'warning'
})

const statusText = computed(() => {
  return authStore.user?.status === 'ACTIVE' ? t('dashboard.profile.card.statusActive') : t('dashboard.profile.card.statusDisabled')
})

const storagePercentage = computed(() => {
  const used = authStore.user?.storageUsed || 0
  const quota = authStore.user?.storageQuota || 1
  return Math.round((used / quota) * 100)
})

// 格式化文件大小
const formatFileSize = (bytes: number): string => {
  if (bytes === 0) return '0 B'
  const k = 1024
  const sizes = ['B', 'KB', 'MB', 'GB', 'TB']
  const i = Math.floor(Math.log(bytes) / Math.log(k))
  return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
}

// 选项卡切换
const handleTabChange = (tabName: string) => {
  console.log('切换到选项卡:', tabName)
}

// 头像上传处理
const handleUploadAvatar = () => {
  avatarDialogVisible.value = true
}

const handleAvatarChange = (file: any) => {
  const isImage = file.raw.type.startsWith('image/')
  const isLt2M = file.raw.size / 1024 / 1024 < 2

  if (!isImage) {
    ElMessage.error(t('dashboard.profile.avatarDialog.error_format'))
    return false
  }
  if (!isLt2M) {
    ElMessage.error(t('dashboard.profile.avatarDialog.error_size'))
    return false
  }

  // 保存选择的文件
  selectedFile.value = file.raw
  // 生成预览URL
  previewUrl.value = URL.createObjectURL(file.raw)
  return true
}

const handleConfirmUpload = async () => {
  if (!selectedFile.value) {
    ElMessage.warning(t('dashboard.profile.avatarDialog.error_select'))
    return
  }

  uploading.value = true
  try {
    // 调用头像上传API
    const response = await uploadAvatar(selectedFile.value)

    if (response.code === 200) {
      // 更新authStore中的用户头像URL
      if (authStore.user) {
        authStore.user.avatarUrl = response.data
      }

      // 更新头像版本号，强制刷新缓存
      authStore.updateAvatarVersion()

      // 强制触发响应式更新
      await authStore.getCurrentUser()

      ElMessage.success(t('dashboard.profile.avatarDialog.success'))
      avatarDialogVisible.value = false
      previewUrl.value = ''
      selectedFile.value = null
    } else {
      ElMessage.error(response.message || t('dashboard.profile.avatarDialog.fail'))
    }
  } catch (error: any) {
    console.error('头像上传失败:', error)
    ElMessage.error(error.message || t('dashboard.profile.avatarDialog.fail'))
  } finally {
    uploading.value = false
  }
}

const handleCloseAvatarDialog = () => {
  if (previewUrl.value) {
    URL.revokeObjectURL(previewUrl.value)
    previewUrl.value = ''
  }
  selectedFile.value = null
  avatarDialogVisible.value = false
}

// 页面初始化
onMounted(() => {
  // 确保用户信息已加载
  if (!authStore.user) {
    authStore.getCurrentUser()
  }
})
</script>

<style lang="scss" scoped>
.profile-view {
  padding: 24px;
  max-width: 1200px;
  margin: 0 auto;
  background-color: var(--bg-color-primary);
  min-height: calc(100vh - 60px);
  transition: background-color 0.3s ease;
}

.profile-header {
  margin-bottom: 32px;

  .page-title {
    font-size: 28px;
    font-weight: 600;
    color: var(--text-color-primary);
    margin: 0 0 8px 0;
    transition: color 0.3s ease;
  }

  .page-subtitle {
    font-size: 16px;
    color: var(--text-color-secondary);
    margin: 0;
    transition: color 0.3s ease;
  }
}

.profile-card {
  background-color: var(--bg-color-tertiary);
  border-radius: 16px;
  padding: 32px;
  margin-bottom: 32px;
  border: 1px solid var(--border-color-light);
  display: grid;
  grid-template-columns: auto 1fr auto;
  gap: 32px;
  align-items: center;
  transition: all 0.3s ease;

  .avatar-section {
    display: flex;
    flex-direction: column;
    align-items: center;
    gap: 16px;

    .el-button {
      font-size: 12px;
    }
  }

  .info-section {
    .user-name {
      font-size: 24px;
      font-weight: 600;
      color: var(--text-color-primary);
      margin: 0 0 8px 0;
      transition: color 0.3s ease;
    }

    .real-name {
      font-size: 16px;
      color: var(--text-color-secondary);
      margin: 0 0 8px 0;
      transition: color 0.3s ease;
    }

    .user-email {
      font-size: 14px;
      color: var(--text-color-secondary);
      margin: 0 0 16px 0;
      transition: color 0.3s ease;
    }

    .user-badges {
      display: flex;
      gap: 8px;
    }
  }

  .stats-section {
    display: flex;
    flex-direction: column;
    gap: 16px;

    .stat-item {
      text-align: center;

      .stat-value {
        display: block;
        font-size: 18px;
        font-weight: 600;
        color: var(--text-color-primary);
        margin-bottom: 4px;
        transition: color 0.3s ease;
      }

      .stat-label {
        font-size: 12px;
        color: var(--text-color-secondary);
        transition: color 0.3s ease;
      }
    }
  }
}

.profile-tabs {
  background-color: var(--bg-color-tertiary);
  border-radius: 16px;
  padding: 24px;
  border: 1px solid var(--border-color-light);
  transition: all 0.3s ease;

  :deep(.el-tabs__header) {
    margin-bottom: 24px;
  }

  :deep(.el-tabs__nav-wrap) {
    &::after {
      background-color: var(--border-color-light);
    }
  }

  :deep(.el-tabs__item) {
    color: var(--text-color-secondary);
    
    &.is-active {
      color: var(--theme-primary);
    }
  }

  :deep(.el-tabs__active-bar) {
    background-color: var(--theme-primary);
  }
}

// 头像上传对话框样式
.avatar-upload {
  .upload-area {
    border: 2px dashed var(--border-color-base);
    border-radius: 8px;
    padding: 40px 20px;
    text-align: center;
    transition: border-color 0.3s ease;

    &:hover {
      border-color: var(--theme-primary);
    }

    .upload-icon {
      font-size: 48px;
      color: var(--text-color-tertiary);
      margin-bottom: 16px;
    }

    .upload-text {
      p {
        margin: 0 0 8px 0;
        color: var(--text-color-primary);
        transition: color 0.3s ease;
      }

      .upload-hint {
        font-size: 12px;
        color: var(--text-color-secondary);
        transition: color 0.3s ease;
      }
    }
  }

  .avatar-preview {
    margin-top: 20px;
    text-align: center;

    img {
      width: 120px;
      height: 120px;
      border-radius: 50%;
      object-fit: cover;
      border: 2px solid var(--border-color-light);
    }
  }
}

// 响应式设计
@media (max-width: 768px) {
  .profile-view {
    padding: 16px;
  }

  .profile-card {
    grid-template-columns: 1fr;
    text-align: center;
    gap: 24px;
  }

  .stats-section {
    flex-direction: row;
    justify-content: center;
  }
}
</style>
